<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="value.name" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model="value.age"/>
    </div>
    <div>
      <span>性别:</span>
      <select v-model="value.sex">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="add">添加/修改</button>
    </div>
    <div>
      <table
        border="1"
        cellpadding="10"
        cellspacing="0"
      >
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item,index) in arr" :key="item.id">
          <td>{{ item.id }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.sex }}</td>
          <td>
            <button @click="del(index)">删除</button>
            <button @click="edit(item)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      flag:false,
      value: {
        id:'',
        name:'',
        age:'',
        sex:'男'
      },
      arr:[{
        id:'1',
        name:'tom',
        age:19,
        sex:'男',
      },
      {
        id:'1',
        name:'tom',
        age:19,
        sex:'男',
      }]
    }
  },
  methods:{
del(a) {
  this.arr.splice(a,1)
},
add() {
  if (this.flag === false) {
    if (this.value.name && this.value.age && this.value.sex) {
      this.value['id'] = this.arr.length + 1
      this.arr.push(this.value)
      this.value = {}
    } else {
      alert('q输入全部内容')
    }
  }
  else {
          // console.log(index);
          if (this.value.name && this.value.age && this.value.sex) {
              let {
                  id,
                  name,
                  age,
                  sex
              } = this.value;
              // console.log(id);
              //循环遍历查找到并修改
              this.arr.forEach(item => {
                  //查找到相对于的item
                  if (item.id == id) {
                      item.name = name;
                      item.age = age;
                      item.sex = sex;
                  }
              })
            this.value={
                 id: '',
                 name: '',
                age: '',
                sex: '男'
                 }
              // console.log(this.arr);
          } else {
              alert('请输入全部内容')
          }
          this.flag = false
      }
   },
   edit(item) {
      this.value.name = item['name']
      this.value.age = item['age']
      this.value.sex = item['sex']
      this.value.id = item['id']
      this.flag = true
}
  }
}
</script>

